﻿using System;
using System.Collections.Generic;
using System.Reflection;
using Backend.JYD.Config.Watcher;

namespace Backend.JYD.Config
{
    public class WatcherFactory
    {
        /// <summary>
        /// 当前实例
        /// </summary>
        private static Dictionary<string, FileWatcher> _FileWatchers = new Dictionary<string, FileWatcher>();

        /// <summary>
        /// 锁定（初次加载）
        /// </summary>
        private static object _lockPad;

        #region 初始化

        public static void Stop()
        {
            if (_FileWatchers != null)
            {
                foreach (KeyValuePair<string, FileWatcher> pair in _FileWatchers)
                {
                    pair.Value.Stop();
                }
            }
            _FileWatchers = new Dictionary<string, FileWatcher>();
        }

        public static void Start()
        {
            var configs = AppConfigs<WatcherConfig>.Instance.Configs;
            if (configs== null) return;
            foreach (KeyValuePair<string, WatcherConfig> pair in configs)
            {
                WatcherConfig config = pair.Value;
                IWatchExecuter executer = null;
                try
                {
                     string[] vals = config.Executer.Split(new char[] { ',' });
                     if (vals.Length != 2) throw new ArgumentNullException("it's error that the wacther section's attribute : \"executer\"");

                    string codeBase = Assembly.GetExecutingAssembly().CodeBase;
                    int pos = codeBase.LastIndexOf("/");
                    executer = (IWatchExecuter)Assembly.Load(vals[1].Trim()).CreateInstance(vals[0].Trim());
                    CreateInstance(config, executer);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

        }


        /// <summary>
        /// 获取对象服务工厂实例
        /// </summary>
        /// <returns></returns>
        private static void CreateInstance(WatcherConfig config, IWatchExecuter executer)
        {
            if (!_FileWatchers.ContainsKey(config.Name))
            {
                _lockPad = new object();
                lock (_lockPad)
                {
                    if (!_FileWatchers.ContainsKey(config.Name))
                    {
                        FileWatcher watcher = new FileWatcher(config, executer);
                        watcher.Init();

                        _FileWatchers.Add(config.Name, watcher);
                    }
                }
            }

            //return _Instance;
        }

        #endregion

    }
}
